package oa.hleast.xswl.controller.admin.questionnaire;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.enums.QueryModeEnum;
import oa.hleast.common.result.Result;
import oa.hleast.common.result.ResultCode;
import oa.hleast.xswl.pojo.domain.questionnaire.QmsAnswer;
import oa.hleast.xswl.pojo.domain.questionnaire.QmsProblem;
import oa.hleast.xswl.pojo.domain.questionnaire.QmsQuestionnaire;
import oa.hleast.xswl.pojo.form.questionnaire.QmsProblemForm;
import oa.hleast.xswl.pojo.vo.questionnaire.QmsAnswerVo;
import oa.hleast.xswl.pojo.vo.questionnaire.QmsProblemVo;
import oa.hleast.xswl.service.ISysCommonConfigService;
import oa.hleast.xswl.service.questionnaire.QmsAnswerService;
import oa.hleast.xswl.service.questionnaire.QmsProblemService;
import oa.hleast.xswl.service.questionnaire.QmsQuestionnaireService;
import oa.hleast.xswl.service.questionnaire.QuestionnaireService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Api(tags = "【系统管理】答题模块问卷管理")
@RestController("AdminQuestionnaireController")
@RequestMapping("/api.admin/v1/questionnaires")
@Slf4j
@AllArgsConstructor
public class QuestionnaireController {

    /**
     * 问卷问题表(QmsQuestionnaire)接口
     */
    private final QmsQuestionnaireService qmsQuestionnaireService;
    /**
     * 问卷问题答案表(QmsAnswer)接口
     */
    private final QmsAnswerService qmsAnswerService;
    /**
     * 问卷问题表(QmsProblem)接口
     */
    private final QmsProblemService qmsProblemService;
    /**
     * 问卷管理
     */
    private final QuestionnaireService questionnaireService;
    /**
     * 通用配置接口
     */
    private final ISysCommonConfigService commonConfigService;

    /**
     *问卷详情
     */
    @ApiOperation(value = "问卷详情", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "path", dataType = "Long",dataTypeClass = Long.class)
    @GetMapping("/main/{id}")
    public Result detail(@PathVariable Long id) {
        return Result.success(qmsQuestionnaireService.getById(id));
    }

    /**
     * 试卷分页查询
     * @param queryMode
     * @param page
     * @param limit
     * @param questionnaireContent
     * @return
     */
    @ApiOperation(value = "试卷列表分页", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "queryMode", paramType = "query", dataType = "QueryModeEnum", dataTypeClass = QueryModeEnum.class),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "limit", value = "每页数量", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "questionnaireContent", value = "问卷标题", paramType = "query", dataType = "String", dataTypeClass = String.class),
    })
    @GetMapping("/questionnaire")
    public Result Questionnairelist(
            String queryMode,
            Integer page,
            Integer limit,
            String questionnaireContent
    ) {
        List<QmsQuestionnaire> questionnaireContentList =null;
        QueryModeEnum queryModeEnum = QueryModeEnum.getValue(queryMode);
        switch (queryModeEnum) {
            case PAGE:
                LambdaQueryWrapper<QmsQuestionnaire> queryWrapper = new LambdaQueryWrapper<QmsQuestionnaire>()
                        .like(StrUtil.isNotBlank(questionnaireContent), QmsQuestionnaire::getTitle, questionnaireContent)
                        .orderByDesc(QmsQuestionnaire::getGmtModified)
                        .orderByDesc(QmsQuestionnaire::getGmtCreate);
                Page<QmsQuestionnaire> result = qmsQuestionnaireService.page(new Page<>(page, limit), queryWrapper);
                List<QmsQuestionnaire> records = result.getRecords();
                /*records.forEach(x->{
                    String questionnaireContents = x.getTitle();
                    questionnaireContentList.add(questionnaireContents);
                });*/
                questionnaireContentList= qmsQuestionnaireService.list();
                return Result.success(questionnaireContentList, result.getTotal());
            default:
                return Result.failed(ResultCode.QUERY_MODE_IS_NULL);

        }
    }

    /**
     * 问题分页查询
     * @param queryMode
     * @param page
     * @param limit
     * @param problemTitle
     * @return
     */
    @ApiOperation(value = "题目列表分页", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "queryMode", paramType = "query", dataType = "QueryModeEnum", dataTypeClass = QueryModeEnum.class),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "limit", value = "每页数量", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name="questionnaireId",value = "试卷id",paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "problemTitle", value = "题干", paramType = "query", dataType = "String", dataTypeClass = String.class),
    })
    @GetMapping("/problem")
    public Result Problemlist(
            String queryMode,
            Integer page,
            Integer limit,
            Integer questionnaireId,
            String problemTitle
    ) {
        List<QmsProblem> problemTitleList;
        QueryModeEnum queryModeEnum = QueryModeEnum.getValue(queryMode);
        switch (queryModeEnum) {
            case PAGE:
                LambdaQueryWrapper<QmsProblem> queryWrapper = new LambdaQueryWrapper<QmsProblem>()
                        .like(StrUtil.isNotBlank(problemTitle), QmsProblem::getQuestionnaireId, questionnaireId)
                        .orderByAsc(QmsProblem::getProblemNumber)
                        .orderByDesc(QmsProblem::getGmtModified)
                        .orderByDesc(QmsProblem::getGmtCreate);
                Page<QmsProblem> result = qmsProblemService.page(new Page<>(page, limit), queryWrapper);

                problemTitleList=qmsProblemService.list(new LambdaQueryWrapper<QmsProblem>().eq(QmsProblem::getQuestionnaireId,questionnaireId));
                return Result.success(problemTitleList, result.getTotal());
            default:
                return Result.failed(ResultCode.QUERY_MODE_IS_NULL);

        }
    }

    /**
     * 新增试卷
     * @param questionnaire
     * @return
     */
    @Transactional
    @ApiOperation(value = "新增试卷", httpMethod = "POST")
    @PostMapping("/addQuestionnaire")
    public Result addQuestionnaire(@RequestBody QmsQuestionnaire questionnaire){
        boolean status= qmsQuestionnaireService.addQuestionnaire(questionnaire);
        return Result.judge(status);
    }

    /**
     * 修改试卷
     * @param qmsQuestionnaire
     * @return
     */
    @Transactional
    @ApiOperation(value = "修改试卷", httpMethod = "POST")
    @PostMapping("/updateQuestionnaire")
    public Result updateQuestionnaire(@RequestBody QmsQuestionnaire qmsQuestionnaire){
        boolean status=qmsQuestionnaireService.updateQuestionnaire(qmsQuestionnaire);
        return Result.judge(status);
    }

    /**
     * 删除试卷
     * @param ids id集合
     * @return
     */
    @Transactional
    @ApiOperation(value = "删除试卷", httpMethod = "GET")
    @ApiImplicitParam(name = "ids", value = "id集合", required = true, paramType = "query", dataType = "String",dataTypeClass = String.class)
    @GetMapping("/deleteQuestionnaire/{ids}")
    public Result deleteQuestionnaire(@PathVariable("ids") String ids ){
        boolean status=qmsQuestionnaireService.deleteQuestionnaire(ids);
        return Result.judge(status);
    }


    /**
     *  设置答题时间
     */
    @ApiOperation(value = "设置答题时间", httpMethod = "PATCH")
    @PatchMapping(value = "/time")
    public Result patchTime(@RequestBody QmsQuestionnaire questionnaire) {
        Long id = Long.valueOf(commonConfigService.getByConfigKey("questionnaireKey").getValue());
        LambdaUpdateWrapper<QmsQuestionnaire> updateWrapper = new LambdaUpdateWrapper<QmsQuestionnaire>().eq(QmsQuestionnaire::getId, id);
        updateWrapper.set(questionnaire.getProblemTime() != null, QmsQuestionnaire::getProblemTime, questionnaire.getProblemTime());
        boolean status = qmsQuestionnaireService.update(updateWrapper);
        return Result.judge(status);
    }

    /**
     * 设置问卷生效or失效
     */
    @ApiOperation(value = "修改问卷状态", httpMethod = "PATCH")
    @PatchMapping(value = "/patch")
    public Result patch(@RequestBody QmsQuestionnaire questionnaire) {
        Long id = Long.valueOf(commonConfigService.getByConfigKey("questionnaireKey").getValue());
        LambdaUpdateWrapper<QmsQuestionnaire> updateWrapper = new LambdaUpdateWrapper<QmsQuestionnaire>().eq(QmsQuestionnaire::getId, id);
        updateWrapper.set(questionnaire.getDisplay() != null, QmsQuestionnaire::getDisplay, questionnaire.getDisplay());
        boolean status = qmsQuestionnaireService.update(updateWrapper);
        return Result.judge(status);
    }

    /**
     *试题详情
     */
    @ApiOperation(value = "试题详情", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "path", dataType = "Long",dataTypeClass = Long.class)
    @GetMapping("/qmsProblem/{id}")
    public Result qmsProblem(@PathVariable("id") Long id) {
        QmsProblem qmsProblem = qmsProblemService.getById(id);
        List<QmsAnswer> list = qmsAnswerService.list(new LambdaUpdateWrapper<QmsAnswer>().eq(QmsAnswer::getProblemId, id));
        List<QmsAnswerVo> qmsAnswerVoList = new ArrayList<>();
        list.forEach(item->{
            QmsAnswerVo qmsAnswerVo = new QmsAnswerVo();
            BeanUtil.copyProperties(item,qmsAnswerVo);
            qmsAnswerVoList.add(qmsAnswerVo);
        });
        QmsProblemVo qmsProblemVo = new QmsProblemVo();
        BeanUtil.copyProperties(qmsProblem,qmsProblemVo);
        qmsProblemVo.setQmsAnswerVoList(qmsAnswerVoList);
        return Result.success(qmsProblemVo);
    }

    @ApiOperation(value = "简略试题列表", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "path", dataType = "Long",dataTypeClass = Long.class)
    @GetMapping("/qmsProblem")
    public Result questionsList(){
        List<String> problemTitleList = new ArrayList<>();
        Long id = Long.valueOf(commonConfigService.getByConfigKey("questionnaireKey").getValue());
        List<QmsProblem> list = qmsProblemService.list(new LambdaUpdateWrapper<QmsProblem>().eq(QmsProblem::getQuestionnaireId, id));
        list.forEach(x->{
            String problemTitle = x.getProblem();
            problemTitleList.add(problemTitle);

        });
        return Result.success(problemTitleList);
    }

    /**
     * 新增题目
     */
    @Transactional
    @ApiOperation(value = "新增题目", httpMethod = "POST")
    @PostMapping("/addProblem")
    public Result addProblem(@RequestBody QmsProblemForm body) {
        Long id = Long.valueOf(body.getQuestionnaireKey());
        QmsProblem qmsProblem = new QmsProblem();
        BeanUtil.copyProperties(body,qmsProblem,"id");
        qmsProblem.setQuestionnaireId(id);
        boolean status = qmsProblemService.save(qmsProblem);
        List<QmsAnswer> qmsAnswers = qmsProblemService.saveAnswer(body.getQmsAnswerVoList(), qmsProblem.getId(), id);

        /*//前端传值没有分数 所以添加固定数值1
        qmsAnswers.forEach(qmsAnswer -> {
            qmsAnswer.setPoints("1");
        });*/

        boolean saveBatch = qmsAnswerService.saveBatch(qmsAnswers);

        return Result.judge(status);
    }

    /**
     * 修改题目
     */
    @Transactional
    @ApiOperation(value = "修改题目", httpMethod = "POST")
    @PostMapping("/updateProblem")
    public Result updateProblem(@RequestBody QmsProblemForm body) {
        Long id = Long.valueOf(body.getQuestionnaireKey());
        QmsProblem qmsProblem = new QmsProblem();
        BeanUtil.copyProperties(body,qmsProblem);
        qmsProblem.setGmtModified(new Date());
        qmsProblem.setQuestionnaireId(id);
        List<QmsAnswer> list = qmsAnswerService.list(new LambdaUpdateWrapper<QmsAnswer>().eq(QmsAnswer::getProblemId, body.getId()));

        boolean status = qmsProblemService.updateById(qmsProblem);

        if(body.getQmsAnswerVoList().size() != list.size()){
            //删除所有答案数据
            list.forEach(x->{
                qmsAnswerService.removeByIds(Arrays.asList(x.getId().toString().split(",")));
            });
            log.info("size={}",body.getQmsAnswerVoList().size());
            List<QmsAnswer> qmsAnswers = qmsProblemService.saveAnswer(body.getQmsAnswerVoList(), qmsProblem.getId(), id);

            /*//前端传值没有分数 所以添加固定数值1
            qmsAnswers.forEach(qmsAnswer -> {
                qmsAnswer.setPoints("1");
            });*/

            boolean batch = qmsAnswerService.saveBatch(qmsAnswers);
        }else {
            List<QmsAnswer> qmsAnswers = qmsProblemService.updateAnswer(body.getQmsAnswerVoList(), body.getId(), id);
            boolean updateBatchById = qmsAnswerService.updateBatchById(qmsAnswers);
        }
        return Result.judge(status);
    }

    /**
     * 删除题目
     */
    @Transactional
    @ApiOperation(value = "删除题目", httpMethod = "GET")
    @ApiImplicitParam(name = "ids", value = "id集合", required = true, paramType = "query", dataType = "String",dataTypeClass = String.class)
    @GetMapping("/deleteProblem/{ids}")
    public Result deleteProblem(@PathVariable("ids") String ids) {
        boolean status = qmsProblemService.removeByIds(Arrays.asList(ids.split(",")));
        List<QmsAnswer> list = qmsAnswerService.list(new LambdaUpdateWrapper<QmsAnswer>().eq(QmsAnswer::getProblemId, ids));
        list.forEach(x->{
            qmsAnswerService.removeByIds(Arrays.asList(x.getId().toString().split(",")));
        });
        return Result.judge(status);
    }

    /**
     * 设置题号
     */
    @ApiOperation(value = "设置考题序号", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "问卷id", required = true, paramType = "path", dataType = "Long",dataTypeClass = Long.class),
            @ApiImplicitParam(name = "member", value = "实体JSON对象", required = true, paramType = "body", dataType = "QmsQuestionnaire",dataTypeClass = QmsQuestionnaire.class)
    })
    @GetMapping(value = "/patchProblem/{id}")
    public Result patchProblem(@PathVariable Long id, @RequestBody QmsProblem problem) {
        LambdaUpdateWrapper<QmsProblem> updateWrapper = new LambdaUpdateWrapper<QmsProblem>().eq(QmsProblem::getId, id);
        updateWrapper.set(problem.getProblemNumber() != null, QmsProblem::getProblemNumber, problem.getProblemNumber());
        boolean status = qmsProblemService.update(updateWrapper);
        return Result.judge(status);
    }

    /**
     * 问卷预览
     */
    @ApiOperation(value = "问卷预览", httpMethod = "GET")
    @GetMapping("/preview/{idQuestionnaire}")
    public Result preview(@PathVariable Long idQuestionnaire) {
        return Result.success(questionnaireService.getAntiStressQuestionnaire(idQuestionnaire));
    }


}
